package com.situ.mall.filter;

import java.io.IOException;
import java.nio.file.Path;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.mall.entity.Result;
import com.situ.mall.entity.User;

@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		//将request和response转换为HttpServlet格式的
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		//项目名到当前jsp文件的路径（意思就是在这个项目首页到文件的路径）
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath的路径为 : " + servletPath);
		
		int lastIndex = servletPath.lastIndexOf(".");
		String extension = "";
		if (lastIndex != -1) {
			extension = servletPath.substring(lastIndex); // .js   .css  .png
		}
		System.out.println("extension = " + extension);

		// 对特殊的请求不需要登录验证
		if (".shtml".equals(extension) 
				|| "/user/login.action".equals(servletPath)
				|| "/user/loginIndex.action".equals(servletPath)
				|| "/user/getLoginListPage.action".equals(servletPath)
				|| "/user/roleLogin.action".equals(servletPath)
				|| "/checkCode".contentEquals(servletPath)
				|| "/fail.jsp".contentEquals(servletPath)
				|| ".js".equals(extension)
				|| ".css".equals(extension)
				|| ".com/css".equals(extension)
				|| ".jpg".equals(extension)
				|| ".ttf".equals(extension)
				|| ".woff2".equals(extension)
				|| ".woff".equals(extension)
				|| ".png".equals(extension)) {
			chain.doFilter(request, response);
		} else {// 需要验证
			System.out.println("未通过特殊请求");
			HttpSession session = httpServletRequest.getSession();
			User user = (User)session.getAttribute("user");
			// user是null，没有登录情况下，需要重定向到登录界面，但是访问user_login.jsp
			// 也会被拦截，也需要登录。问题就是：要去登录界面但是到登录界面要求你必须是登录状态。
			// 解决方法就是：给一些特殊的请求不进行登录验证，例如：user_login.jsp、/loginServlet
			if (user == null ) {
				
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/user/getLoginListPage.action");
				return ;
			}
			System.out.println("role = " + user.getRole() );
			if (user.getRole() == 1) {
				Result.error("该页面需要管理员权限才可进入");
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/user/roleLogin.action");
				return;
			}
			  
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void destroy() {
	}

}
